#!/bin/bash

# 需要使用ssh免密操作
# 使用ssh-keygen命令生成公钥，并将公钥写入YOCTO服务器的.ssh/authorized_keys文件中

WORK_PATH=$(readlink -f ${0} | xargs dirname)
ENV_PATH="${WORK_PATH}/env"
CODE_PATH="${WORK_PATH}/src"
X86_SDK_L_PATH="${ENV_PATH}/x86_sdk"
CDC_SDK_L_PATH="${ENV_PATH}/cdc_sdk"
IMAGE_PATH="${ENV_PATH}/image"
X86_DEB_PATH="${ENV_PATH}/x86_deb"
X86_INSTALL_L_PATH="${ENV_PATH}/x86_install"
X86_INSTALL_D_PATH="env/x86_install"
CDC_DEB_PATH="${ENV_PATH}/cdc_deb"
REPO_URL="https://gitlab.geniie.net/BEVS3CDC/dn-bevs3-cdc"
BEV_RELEASE_URL="https://art.geniie.net/artifactory/bevs3cdc-generic-tier1/devops/dn-cdc-lvgvm-26bev-repo/release"
LIST_FILE="listing"
IMAGES_FILE="${ENV_PATH}/IMAGES_FILE"
BEV_DOCKER_FILE="arene-image-cockpit-cdc-genericx86-64.tar.bz2"
BEV_DEBUG_FILE="x86-ubuntu/rootfs/debug/genericx86-64/${BEV_DOCKER_FILE}"
BEV_DOCKER_REGISTRY="art.geniie.net/bevs3cdc-docker-tier1/dn-bevs3cdc-runtime-dbg"
DOCKEER_PULL_USER="xiufd@neusoft.com"
DOCKEER_PULL_PASSWD='!QAZ1qaz'

LOG_PATH="${WORK_PATH}/log"
DATE=$(date +%Y%m%d-%H%M%S)
DATE_H=$(date +%Y%m%d-%H)
start_time_s=$(date +%s)
USER_PASSWORD='bevdev11!!'
########################################################################################################################
BUILD_BRANCH="feature/yocto-build-bev"
REPO_TARGET=(
    # dn-cdc-lvgvm-hal-cec-impl-qc
    # dn-cdc-lvgvm-hal-input
    # dn-cdc-lvgvm-hal-input-impl-qc
    # dn-cdc-lvgvm-hal-usb
    dn-cdc-lvgvm-hal-usb-impl-qc
    # dn-cdc-lvgvm-hal-lansrv
    # dn-cdc-lvgvm-hal-lansrv-impl-qc
    # dn-cdc-lvgvm-hal-most
    # dn-cdc-lvgvm-hal-most-impl-qc
    # dn-cdc-lvgvm-hal-avclan
    # dn-cdc-lvgvm-hal-avclan-impl-qc
    # dn-cdc-lvgvm-hal-backup-impl-qc
    # dn-cdc-lvgvm-hal-power
    # dn-cdc-lvgvm-hal-power-impl-qc
    # dn-cdc-lvgvm-hal-cinemoex
    # dn-cdc-lvgvm-hal-bluetooth
    # dn-cdc-lvgvm-hal-wifi
    # dn-cdc-lvgvm-hal-vehicle-impl-qc
    # dn-cdc-lvgvm-hal-dtv-api
    # dn-cdc-lvgvm-hal-radio
    # dn-cdc-lvgvm-hal-sxm
    # dn-cdc-lvgvm-systemd-collection
    dn-cdc-lvgvm-pf-system-append-common
    # dn-cdc-lvgvm-pf-system-append-qcom
    # dn-cdc-lvgvm-pf-system-data-qcom
    # dn-cdc-lvgvm-hal-stub-common
)

SDK_TARGET=(
    x86-ubuntu/toolchain/debug:${ENV_PATH}:x86_sdk
    sa8255p-dn-cdc/toolchain/debug:${ENV_PATH}:cdc_sdk
)
########################################################################################################################

function log()
{
    echo "----------------------------------------------------------------------------------------------------------------"
    echo ${1}
    echo "---"
}

function start_run
{
    [[ -e ${IMAGE_PATH} ]] || mkdir -p ${IMAGE_PATH}
    [[ -e ${X86_INSTALL_PATH} ]] || mkdir -p ${X86_INSTALL_PATH}
    [[ -e ${X86_DEB_PATH} ]] || mkdir -p ${X86_DEB_PATH}
    [[ -e ${CDC_DEB_PATH} ]] || mkdir -p ${CDC_DEB_PATH}
    [[ -e ${CODE_PATH} ]] || mkdir -p ${CODE_PATH}
    [[ -e ${LOG_PATH} ]] || mkdir -p ${LOG_PATH}
    echo "#####################################################"
    echo "# Start Time     : $(date +%Y/%m/%d-%H:%M:%S)"
    echo "#####################################################"
}

function normal_exit
{
    # delete lock file.
    local end_time_s=$(date +%s)
    echo "#####################################################"
    echo "# End Time       : $(date +%Y/%m/%d-%H:%M:%S)"
    echo "# Execution Time : $[ $end_time_s - $start_time_s ]s"
    echo "# The Log log storage path => ${LOG_PATH}"
    echo "#####################################################"
    exit 0
}

function install_docker_image() 
{
    # download docker
    log "[NORMAL ] wget ${BEV_RELEASE_URL}/${1:0:6}/${1}/${BEV_DEBUG_FILE}"
    rm -f ${ENV_PATH}/${BEV_DOCKER_FILE}
    wget ${BEV_RELEASE_URL}/${1:0:6}/${1}/${BEV_DEBUG_FILE} -O ${ENV_PATH}/${BEV_DOCKER_FILE}
    if [[ $? -ne 0 ]]; then
        log "[ERROR ] wget ${BEV_RELEASE_URL}/${1:0:6}/${1}/${BEV_DEBUG_FILE} -O ${ENV_PATH}/${BEV_DOCKER_FILE} ERROR !!!."
        return 1
    fi
    log "[INFO] [docker import ${ENV_PATH}/${BEV_DOCKER_FILE} ${BEV_DOCKER_REGISTRY}:${1}]"
    docker import ${ENV_PATH}/${BEV_DOCKER_FILE} ${BEV_DOCKER_REGISTRY}:${1} || { log "[ERR] [docker import ${ENV_PATH}/${BEV_DOCKER_FILE} ${BEV_DOCKER_REGISTRY}:${1}] ERROR !!!"; exit 1; }
    if [ -e ${IMAGES_FILE} ]; then
        # remove old docker images.
        image_info=$(cat ${IMAGES_FILE})
        for image in ${image_info[@]}; do
            log "[NORMAL ] docker rmi old images=${image}"
            docker rmi ${image}
        done
    fi
    echo "${BEV_DOCKER_REGISTRY}:${1}" > ${IMAGES_FILE}
}

function install_sdk()
{
    read -p "Please enter your SDK version (eg:20250409_0.9.0.0-rc.2):" ver
    rm -rf ${ENV_PATH}/*.sh
    for target in ${SDK_TARGET[@]}; do
        local param=(${target//:/ })
        local p_1=${param[0]}
        local p_2=${param[1]}
        local p_3=${param[2]}
        pushd ${p_2}
                rm -f ${LIST_FILE}
                wget --no-remove-listing -O ${LIST_FILE} ${BEV_RELEASE_URL}/${ver:0:6}/${ver}/${p_1}
                if [[ -e ${LIST_FILE} ]]; then
                    sdk_file=$(grep -E .*\.sh ${LIST_FILE} | cut -d "\"" -f2)
                    wget ${BEV_RELEASE_URL}/${ver:0:6}/${ver}/${p_1}/${sdk_file}
                    if [[ -e ${sdk_file} ]]; then
                        chmod +x ${sdk_file}
                        ./${sdk_file} -y -d ./${p_3}
                    fi
                fi
        popd
    done
}

function git_clone_repo()
{
    pushd ${CODE_PATH}
        log "[INFO ] git ${1} operations start !!!."
        if [[ -e ${1} ]]; then
            pushd ${1}
                git reset --hard HEAD
                git clean -df
                git remote update origin --prune
                git checkout master || { echo ">>>>>>[ERROR] [git checkout master] ERROR !!!"; return 1; }
                git pull
                branch_name=$(git branch -r | grep "origin/${BUILD_BRANCH}")
                if [[ -n "${branch_name}" ]]; then
                    git checkout ${BUILD_BRANCH} || { echo ">>>>>>[ERROR] [git checkout ${BUILD_BRANCH}] ERROR !!!"; return 1; }
                else
                    echo ">>>>>>[ERROR] [${1} origin not found ${BUILD_BRANCH} branch] ERROR !!!"
                    return 1
                fi
            popd
        else
            git clone --progress "${REPO_URL}/${1}.git" ${1}
            pushd ${1}
            {
                git pull
                branch_name=$(git branch -r | grep "origin/${BUILD_BRANCH}")
                if [[ -n "${branch_name}" ]]; then
                    git checkout ${BUILD_BRANCH} || { echo ">>>>>>[ERROR] [git clone and checkout ${BUILD_BRANCH}] ERROR] ERROR !!!"; return 1; }
                else
                    echo ">>>>>>[ERROR] [${1} origin not found ${BUILD_BRANCH} branch] ERROR !!!"
                    return 1
                fi
            }
            popd
        fi
        log "[INFO ] git ${1} operations end  !!!."
    popd
}

function build_create_image()
{
    local base_image=$(head -n 1 ${IMAGES_FILE})
    local current_image="${base_image}_${DATE_H}"
    local current_tag="${base_image##*:}_${DATE_H}"
    local commit_id_file="${IMAGE_PATH}/${current_tag}_commit_id"

    if [[ ${1} == "x86" ]];then
        rm -rf ${IMAGE_PATH}/*
        rm -rf ${X86_DEB_PATH}/*
        rm -rf ${CDC_DEB_PATH}/*
        : > ${commit_id_file}
        for target in ${REPO_TARGET[@]}; do
            git_clone_repo ${target} || { echo ">>>>>>[ERROR] [git_clone_repo ${target}] ERROR !!!"; exit 1; }
            pushd ${CODE_PATH}/${target}
                SRCREV="[${target}]_[${BUILD_BRANCH}]_commit_id = \"$(git rev-parse HEAD)\""
                echo ${SRCREV}  >> ${commit_id_file}
            popd
        done
        deb_path=${X86_DEB_PATH}
        cmake_param="x86-ubuntu"
        source ${X86_SDK_L_PATH}/environment-setup-core2-64-arene-linux || { echo ">>>>>>[ERROR] [source ${X86_SDK_L_PATH}/environment-setup-core2-64-arene-linux] ERROR !!!"; exit 1; }
    else
        rm -rf ${CDC_DEB_PATH}/*
        deb_path=${CDC_DEB_PATH}
        cmake_param="sa8255p-dn-cdc"
        source ${CDC_SDK_L_PATH}/environment-setup-cortexa78c-arene-linux || { echo ">>>>>>[ERROR] [source ${CDC_SDK_L_PATH}/environment-setup-cortexa78c-arene-linux] ERROR !!!"; exit 1; }
    fi
    [[ -e ${deb_path} ]] || mkdir -p ${deb_path}
    rm -rf ${deb_path}/*
    # cockpit_sdk level debug
    local CPU_NUM=$(lscpu | grep "^CPU(s):" | awk '{print $2}')
    make_num=$(( (${CPU_NUM}/4)*3 ))
    for target in ${REPO_TARGET[@]}; do
        pushd ${CODE_PATH}/${target}
            rm -rf build && mkdir build
            pushd build
                cmake .. -DTIER1_BUILD_TARGET="${cmake_param}" || { echo ">>>>>>[ERROR] [cmake .. -DTIER1_BUILD_TARGET=${cmake_param}] ERROR !!!"; exit 1; }
                make all -j${make_num} || { echo ">>>>>>[ERROR] [make all -j${make_num}] ERROR !!!"; exit 1; }
                make package
                cp *.deb ${deb_path}
            popd
            rm -rf build
        popd
    done

    if [[ ${1} == "x86" ]];then
        rm -rf ${X86_INSTALL_L_PATH}/*
        for deb in $(ls ${deb_path}/*.deb); do
            dpkg -x "${deb}" ${X86_INSTALL_L_PATH}
        done
        
        # 使用 heredoc 确保格式正确
        pushd ${WORK_PATH}
            echo ">>>>>>[INFO] [docker build -t ${current_image}]"
            docker rmi ${current_image}
            docker build -t "${current_image}" -f - . <<EOF
FROM ${base_image}
COPY ./${X86_INSTALL_D_PATH}/. /
CMD ["/bin/bash"]
EOF
#             docker build -t "${current_image}" -f - . <<EOF
# FROM ${base_image}
# COPY ./${X86_INSTALL_D_PATH}/opt/. /opt
# CMD ["/bin/bash"]
# EOF
            (( $? )) && { echo ">>>>>>[ERROR] [docker build -t ${current_image}] ERROR !!!"; exit 1; }
            echo "${current_image}" >> ${IMAGES_FILE}
            echo "docker save ${current_image} | gzip > ${IMAGE_PATH}/${current_tag}.tar.gz"
            docker save ${current_image} | gzip > ${IMAGE_PATH}/${current_tag}.tar.gz
        popd
    fi
}

########################################################
# main
########################################################
while :
do
    echo "#####################################################################"
    echo "#         Please select one of the options below to proceed         #"
    echo "# Options:                                                          #"
    echo "#         1   RELEASE DOCKER IMAGE install                          #"
    echo "#         2   RELEASE SDK install                                   #"
    echo "#         3   x86 SDK build and create image                        #"
    echo "#         4   cdc SDK build                                         #"
    echo "#         0   exit                                                  #"
    echo "#####################################################################"

    read -p "Please enter your options:" options
    echo ""
    
    case ${options} in
            1)
                read -p "Please enter your docker version (eg:20250409_0.9.0.0-rc.2):" ver
                log "[NORMAL] >>>>>>Install RELEASE DOCKER IMAGE Start !<<<<<<"
                start_run
                install_docker_image ${ver}
                normal_exit
                log "[NORMAL] >>>>>>Install RELEASE DOCKER IMAGE End  !<<<<<<"
                ;;
            2)
                log "[NORMAL] >>>>>> RELEASE SDK install Start !<<<<<<"
                start_run
                install_sdk
                normal_exit
                log "[NORMAL] >>>>>> RELEASE SDK install End  !<<<<<<"
                ;;
            3)
                log "[NORMAL] >>>>>> x86 SDK build and create image Start !<<<<<<"
                start_run
                build_create_image "x86"
                normal_exit
                log "[NORMAL] >>>>>> x86 SDK build and create image End  !<<<<<<"
                ;;
            4)
                log "[NORMAL] >>>>>> cdc SDK build and create image Start !<<<<<<"
                start_run
                build_create_image "cdc"
                normal_exit
                log "[NORMAL] >>>>>> cdc SDK build and create image End  !<<<<<<"
                ;;
            0)
                log "[NORMAL] --exit 0--"
                exit 0
                ;;
            *)
                log "[ERROR ] ------wrong option = [ ${options} ]!!!------"
                ;;
    esac
done
